package com.chenc.javathreads.controlleraop.intercetor;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONUtil;
import com.chenc.javathreads.controlleraop.config.RequestWrapper;
import com.chenc.javathreads.controlleraop.dto.ApiDto;
import com.chenc.javathreads.controlleraop.signutil.CaiNiaoSignUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import static com.chenc.javathreads.common.NormalInteceptorEnum.REQUEST_SIGN;

/**
 * @ClassName
 * @Describtion:  做签名验签的拦截
 * @Author:Chenc
 * @Date:2024/1/2 15:48
 * @Version 1.0
 */
@Component
public class SignApiInteceptor implements HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException, ServletException {
        //签名验签的拦截
        //路径在配置中写
        Boolean result = false;
        String sign = StringUtils.isNotEmpty(request.getHeader(REQUEST_SIGN.getValue()))?request.getHeader(REQUEST_SIGN.getValue()):"";
        try{
            String jsonParam = new RequestWrapper(request).getBodyString();
            ApiDto apiDto = JSONUtil.toBean(jsonParam, ApiDto.class);
            String genSign = CaiNiaoSignUtil.sign(apiDto.getJsonBody(), apiDto.getTimeStamp());
            result = sign.equals(genSign);
        }catch(Exception e){
//            result = false;
        }
        if (!result){
//            response.sendRedirect("/cqk/error");
//            request.getRequestDispatcher("/index.html").forward(request, response);
            request.getRequestDispatcher("/cqk/error").forward(request, response);
        }
        return result;
    }
}
